// 全局变量
let currentDeleteKey = null;
let allData = {};

// DOM元素
const addUpdateForm = document.getElementById('addUpdateForm');
const searchForm = document.getElementById('searchForm');
const editForm = document.getElementById('editForm');
const refreshBtn = document.getElementById('refreshBtn');
const clearAllBtn = document.getElementById('clearAllBtn');
const exportBtn = document.getElementById('exportBtn');
const importFile = document.getElementById('importFile');
const dataTableBody = document.getElementById('dataTableBody');
const noDataMessage = document.getElementById('noDataMessage');
const editModal = document.getElementById('editModal');
const deleteModal = document.getElementById('deleteModal');
const notification = document.getElementById('notification');
const searchResult = document.getElementById('searchResult');

// 模态框关闭按钮
const editModalClose = editModal.querySelector('.close');
const deleteModalClose = deleteModal.querySelector('.close');
const confirmDeleteBtn = document.getElementById('confirmDeleteBtn');
const cancelDeleteBtn = document.getElementById('cancelDeleteBtn');

// 初始化
document.addEventListener('DOMContentLoaded', () => {
    loadAllData();
    setupEventListeners();
});

// 设置事件监听器
function setupEventListeners() {
    addUpdateForm.addEventListener('submit', handleAddUpdate);
    searchForm.addEventListener('submit', handleSearch);
    editForm.addEventListener('submit', handleEdit);
    refreshBtn.addEventListener('click', loadAllData);
    clearAllBtn.addEventListener('click', handleClearAll);
    exportBtn.addEventListener('click', handleExport);
    importFile.addEventListener('change', handleImport);
    
    // 模态框事件
    editModalClose.addEventListener('click', () => closeModal(editModal));
    deleteModalClose.addEventListener('click', () => closeModal(deleteModal));
    cancelDeleteBtn.addEventListener('click', () => closeModal(deleteModal));
    confirmDeleteBtn.addEventListener('click', handleDelete);
    
    // 点击模态框外部关闭
    window.addEventListener('click', (event) => {
        if (event.target === editModal) {
            closeModal(editModal);
        }
        if (event.target === deleteModal) {
            closeModal(deleteModal);
        }
    });
}

// 加载所有数据
async function loadAllData() {
    try {
        const response = await fetch('/read_data');
        if (!response.ok) {
            throw new Error('加载数据失败');
        }
        
        allData = await response.json();
        renderDataTable(allData);
        showNotification('数据加载成功', 'success');
    } catch (error) {
        showNotification(`加载数据失败: ${error.message}`, 'error');
        console.error('加载数据失败:', error);
    }
}

// 渲染数据表格
function renderDataTable(data) {
    dataTableBody.innerHTML = '';
    
    if (Object.keys(data).length === 0) {
        noDataMessage.style.display = 'block';
        return;
    }
    
    noDataMessage.style.display = 'none';
    
    Object.entries(data).forEach(([key, value]) => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${escapeHtml(key)}</td>
            <td>${escapeHtml(value)}</td>
            <td>
                <div class="action-buttons">
                    <button class="btn btn-secondary edit-btn" data-key="${escapeHtml(key)}">编辑</button>
                    <button class="btn btn-danger delete-btn" data-key="${escapeHtml(key)}">删除</button>
                </div>
            </td>
        `;
        dataTableBody.appendChild(row);
    });
    
    // 添加编辑和删除按钮事件
    document.querySelectorAll('.edit-btn').forEach(btn => {
        btn.addEventListener('click', () => {
            const key = btn.getAttribute('data-key');
            openEditModal(key, data[key]);
        });
    });
    
    document.querySelectorAll('.delete-btn').forEach(btn => {
        btn.addEventListener('click', () => {
            const key = btn.getAttribute('data-key');
            openDeleteModal(key);
        });
    });
}

// 处理添加/更新数据
async function handleAddUpdate(event) {
    event.preventDefault();
    
    const key = document.getElementById('key').value.trim();
    const value = document.getElementById('value').value.trim();
    
    if (!key || !value) {
        showNotification('键和值不能为空', 'error');
        return;
    }
    
    try {
        const response = await fetch('/write_data', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ [key]: value })
        });
        
        if (!response.ok) {
            throw new Error('保存数据失败');
        }
        
        showNotification('数据保存成功', 'success');
        addUpdateForm.reset();
        loadAllData();
    } catch (error) {
        showNotification(`保存数据失败: ${error.message}`, 'error');
        console.error('保存数据失败:', error);
    }
}

// 处理搜索
async function handleSearch(event) {
    event.preventDefault();
    
    const searchKey = document.getElementById('searchKey').value.trim();
    
    if (!searchKey) {
        searchResult.innerHTML = '';
        return;
    }
    
    try {
        // 使用新的单个数据查询接口
        const response = await fetch(`/get/${encodeURIComponent(searchKey)}`);
        
        if (response.status === 404) {
            searchResult.innerHTML = `<div>未找到键为 "${escapeHtml(searchKey)}" 的数据</div>`;
            return;
        }
        
        if (!response.ok) {
            throw new Error('查询数据失败');
        }
        
        const data = await response.json();
        searchResult.innerHTML = `
            <div class="key">键: ${escapeHtml(searchKey)}</div>
            <div class="value">值: ${escapeHtml(data[searchKey])}</div>
        `;
    } catch (error) {
        showNotification(`查询数据失败: ${error.message}`, 'error');
        console.error('查询数据失败:', error);
    }
}

// 打开编辑模态框
function openEditModal(key, value) {
    document.getElementById('editKey').value = key;
    document.getElementById('editValue').value = value;
    editModal.style.display = 'block';
}

// 处理编辑
async function handleEdit(event) {
    event.preventDefault();
    
    const key = document.getElementById('editKey').value;
    const value = document.getElementById('editValue').value.trim();
    
    if (!value) {
        showNotification('值不能为空', 'error');
        return;
    }
    
    try {
        const response = await fetch('/write_data', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ [key]: value })
        });
        
        if (!response.ok) {
            throw new Error('更新数据失败');
        }
        
        showNotification('数据更新成功', 'success');
        closeModal(editModal);
        loadAllData();
    } catch (error) {
        showNotification(`更新数据失败: ${error.message}`, 'error');
        console.error('更新数据失败:', error);
    }
}

// 打开删除确认模态框
function openDeleteModal(key) {
    currentDeleteKey = key;
    deleteModal.style.display = 'block';
}

// 处理删除
async function handleDelete() {
    if (!currentDeleteKey) {
        closeModal(deleteModal);
        return;
    }
    
    try {
        // 使用新的删除接口
        const response = await fetch(`/delete/${encodeURIComponent(currentDeleteKey)}`, {
            method: 'DELETE'
        });
        
        if (response.status === 404) {
            showNotification('要删除的数据不存在', 'error');
            closeModal(deleteModal);
            return;
        }
        
        if (!response.ok) {
            throw new Error('删除数据失败');
        }
        
        showNotification('数据删除成功', 'success');
        closeModal(deleteModal);
        loadAllData();
    } catch (error) {
        showNotification(`删除数据失败: ${error.message}`, 'error');
        console.error('删除数据失败:', error);
    }
}

// 处理清空所有数据
async function handleClearAll() {
    if (!confirm('确定要清空所有数据吗？此操作不可撤销。')) {
        return;
    }
    
    try {
        const response = await fetch('/override', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({})
        });
        
        if (!response.ok) {
            throw new Error('清空数据失败');
        }
        
        showNotification('所有数据已清空', 'success');
        loadAllData();
    } catch (error) {
        showNotification(`清空数据失败: ${error.message}`, 'error');
        console.error('清空数据失败:', error);
    }
}

// 处理导出数据
async function handleExport() {
    try {
        const response = await fetch('/read_data');
        if (!response.ok) {
            throw new Error('获取数据失败');
        }
        
        const data = await response.json();
        const dataStr = JSON.stringify(data, null, 2);
        const dataUri = 'data:application/json;charset=utf-8,'+ encodeURIComponent(dataStr);
        
        const exportFileDefaultName = `data_export_${new Date().toISOString().slice(0, 19).replace(/:/g, '-')}.json`;
        
        const linkElement = document.createElement('a');
        linkElement.setAttribute('href', dataUri);
        linkElement.setAttribute('download', exportFileDefaultName);
        linkElement.click();
        
        showNotification('数据导出成功', 'success');
    } catch (error) {
        showNotification(`导出数据失败: ${error.message}`, 'error');
        console.error('导出数据失败:', error);
    }
}

// 处理导入数据
async function handleImport(event) {
    const file = event.target.files[0];
    if (!file) {
        return;
    }
    
    if (!file.name.endsWith('.json')) {
        showNotification('请选择JSON文件', 'error');
        event.target.value = '';
        return;
    }
    
    try {
        const fileContent = await readFileAsText(file);
        const data = JSON.parse(fileContent);
        
        if (typeof data !== 'object' || data === null) {
            throw new Error('JSON文件内容必须是对象');
        }
        
        // 确保所有值都是字符串
        const stringData = {};
        for (const [key, value] of Object.entries(data)) {
            stringData[key] = String(value);
        }
        
        const response = await fetch('/override', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(stringData)
        });
        
        if (!response.ok) {
            throw new Error('导入数据失败');
        }
        
        showNotification('数据导入成功', 'success');
        loadAllData();
    } catch (error) {
        showNotification(`导入数据失败: ${error.message}`, 'error');
        console.error('导入数据失败:', error);
    } finally {
        event.target.value = '';
    }
}

// 将文件读取为文本
function readFileAsText(file) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = (event) => resolve(event.target.result);
        reader.onerror = (error) => reject(error);
        reader.readAsText(file, 'UTF-8');
    });
}

// 关闭模态框
function closeModal(modal) {
    modal.style.display = 'none';
}

// 显示通知
function showNotification(message, type = 'info') {
    notification.textContent = message;
    notification.className = `notification ${type}`;
    notification.classList.add('show');
    
    setTimeout(() => {
        notification.classList.remove('show');
    }, 3000);
}

// HTML转义，防止XSS攻击
function escapeHtml(unsafe) {
    return unsafe
        .replace(/&/g, "&")
        .replace(/</g, "<")
        .replace(/>/g, ">")
        .replace(/"/g, "&quot;")
        .replace(/'/g, "&#039;");
}